﻿using gAMS_Sacombank;
using gAMS_Sacombank.CommonClass;
using gAMS_Sacombank.AssetService;
using gAMS_Sacombank.Resources;
using gAMS_Sacombank.ViewModels.Common;
using gAMS_Sacombank.Views.SystemRole;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using mvvmCommon;

namespace gAMS_Sacombank.ViewModels.SystemRole
{
    public class UserViewModel : ViewModelBase
    {
        private TLUSERClient tlUserClient;
        public UserViewModel()
        {
            this.actionButton = new ActionButton(this);
            this.messagePop = new MessageAlarmViewModel();
            ActionMenuButton.actionControl.SetAllAction(actionButton, null, actionButton, actionButton, actionButton, actionButton, null);
            this.DoubleClickItemCommand = new RelayCommand(DoubleClickItem);

            ReLoad();

            Messenger.Reset();
            Messenger.Default.Register<ParentMessage>(this, UserEditResponseMessageReceived);
        }             

        private ActionButton actionButton;
        private ObservableCollection<TL_USER> currentData;
        private UserEdit tlUserChild;
        private DateTime _clickTs;

        #region[All Properties]
        //Message Alarm validate
        private MessageAlarmViewModel messagePop;
        public MessageAlarmViewModel MessagePop
        {
            get
            {
                return this.messagePop;
            }

            set
            {
                this.messagePop = value;
                this.OnPropertyChanged("MessagePop");
            }
        }

        private PagedCollectionView tlUser;
        public PagedCollectionView TLUser
        {
            get
            {
                return this.tlUser;
            }

            set
            {
                this.tlUser = value;
                OnPropertyChanged("TLUser");
            }
        }

        private TL_USER currentUser;
        public TL_USER CurrentUser
        {
            get
            {
                return this.currentUser;
            }

            set
            {
                this.currentUser = value;
                OnPropertyChanged("CurrentUser");
            }
        }

        private string brid = "";
        public string BRID
        {
            get
            {
                return this.brid;
            }

            set
            {
                this.brid = value;
                this.OnPropertyChanged("BRID");
            }
        }

        private string subBRDESC = "";
        public string SUBBRDESC
        {
            get
            {
                return this.subBRDESC;
            }

            set
            {
                this.subBRDESC = value;
                this.OnPropertyChanged("SUBBRDESC");
            }
        }

        public ICommand DoubleClickItemCommand { get; private set; }
        
        public List<ItemYesNo> AuthData { get; set; }
        public ObservableCollection<TL_SYSROLE> RoleData { get; set; }
       

        private TL_USER currentSearch = new TL_USER() { TLNANME = "", TLSUBBRID = "", AUTH_STATUS = "", RoleName = CommonResource.lblAll };
        public TL_USER CurrentSearch
        {
            get
            {
                return this.currentSearch;
            }

            set
            {
                this.currentSearch = value;
                this.OnPropertyChanged("CurrentSearch");
            }
        }
        
        #endregion

        #region[Action Functions]

        private void Insert()
        {
            if (this.tlUserChild == null)
            {
                this.tlUserChild = new UserEdit();
                PageAnimation.back.Children.Add(this.tlUserChild);
            }

            Messenger.Default.Send(new ChildMessage() { currentObject = null, isEdit = false, action = ActionMenuButton.Insert });
            PageAnimation.ToBack();        
        }

        private void Edit()
        {
            if (this.tlUserChild == null)
            {
                this.tlUserChild = new UserEdit();
                PageAnimation.back.Children.Add(this.tlUserChild);
            }

            Messenger.Default.Send(new ChildMessage() { currentObject = this.currentUser, isEdit = true, action = ActionMenuButton.Edit });
            PageAnimation.ToBack();   
        }

        private void View()
        {
            if (this.tlUserChild == null)
            {
                this.tlUserChild = new UserEdit();
                PageAnimation.back.Children.Add(this.tlUserChild);
            }

            Messenger.Default.Send(new ChildMessage() { currentObject = this.currentUser, isEdit = false, action = ActionMenuButton.View });
            PageAnimation.ToBack();
        }

        private void Delete()
        {
            this.messagePop.Reset();
            if (this.currentUser.ISAPPROVE.Equals("1"))
            {
                this.messagePop.SetSingleError(CommonResource.lblIsUsing);
                return;
            }

            if (MessageBox.Show(CommonResource.msgDelete, CommonResource.btnDelete, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                //call delete item
                MyHelper.IsBusy();
                this.tlUserClient.DeleteTLUSERAsync(this.currentUser);
            }    
        }

        private void Search()
        {
            try
            {
                this.messagePop.Reset();
                string where = " TLNANME like '%" + (this.currentSearch.TLNANME.Equals("") ? "%" : this.currentSearch.TLNANME) + "%' "
                    + " and RoleName like '%" + (this.currentSearch.RoleName.Equals(CommonResource.lblAll) ? "%" : this.currentSearch.RoleName) + "%' "
                    + " and TLSUBBRID like '%" + (this.currentSearch.TLSUBBRID.Equals("") ? "%" : this.currentSearch.TLSUBBRID) + "%' "
                    + " and AUTH_STATUS like '%" + (this.currentSearch.AUTH_STATUS.Equals("") ? "%" : this.currentSearch.AUTH_STATUS) + "%' "
                    + " and TLNANME != 'admin' ";
                MyHelper.IsBusy();
                this.tlUserClient.GetByTopTLUSERAsync("200", where, "");
            }
            catch (Exception)
            { }
        }

        #endregion

        #region[All Funtions]

        private void UserEditResponseMessageReceived(ParentMessage obj)
        {
            if (obj.currentObject != null)
            {
                this.currentData.Add(obj.currentObject as TL_USER);
            }
            else
            {
                this.messagePop.Reset();
                ActionMenuButton.actionControl.SetAllAction(actionButton, null, actionButton, actionButton, actionButton, actionButton, null);
                PageAnimation.ToFront();
            }
        }   

        private void ReLoad()
        {
            try
            {
                this.tlUserClient = new TLUSERClient();
                
                TLSYSROLEClient roleClient = new TLSYSROLEClient();

                roleClient.GetByTopTLSYSROLEAsync("", "", "");
                roleClient.GetByTopTLSYSROLECompleted += (s, e) =>
                {
                    ObservableCollection<TL_SYSROLE> tempRole;
                    if (e.Result != null && e.Result.Count > 0)                    
                        tempRole = e.Result;                                           
                    else                    
                        tempRole = new ObservableCollection<TL_SYSROLE>();                        
                    
                    tempRole.Add(new TL_SYSROLE() { ROLE_ID = CommonResource.lblAll });
                    this.RoleData = tempRole;
                    this.OnPropertyChanged("RoleData");
                };

               
                this.AuthData = new List<ItemYesNo>()
                {
                    new ItemYesNo(){Id="A", Name=CommonResource.lblApproved},
                    new ItemYesNo(){Id="U", Name=CommonResource.lblDisApprove},
                    new ItemYesNo(){Id="", Name=CommonResource.lblAll}
                };

                this.tlUserClient.GetByTopTLUSERAsync("", " TLNANME != 'admin' ", "");
                this.tlUserClient.GetByTopTLUSERCompleted += new EventHandler<GetByTopTLUSERCompletedEventArgs>(getTopTLUserCompleted);

                this.tlUserClient.DeleteTLUSERCompleted += new EventHandler<DeleteTLUSERCompletedEventArgs>(deletedCompleted);
            }
            catch (Exception ex)
            {
                this.messagePop.SetSingleError(ex.Message);
            }
        }

        private void deletedCompleted(object sender, DeleteTLUSERCompletedEventArgs e)
        {
            try
            {
                //delete successful
                if (e.Result)
                {
                    //remove on current CurrencyData
                    this.currentData.Remove(this.currentUser);
                    this.Refresh();
                }
                else
                    this.messagePop.SetSingleError(CommonResource.errorDelete);
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void getTopTLUserCompleted(object sender, GetByTopTLUSERCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null && e.Result.Count > 0)
                    this.currentData = e.Result;
                else
                    this.currentData = new ObservableCollection<TL_USER>();
                this.Refresh();
            }
            catch (Exception)
            {
                this.messagePop.SetSingleError(CommonResource.errorCannotConnectServer);
            }
            finally
            {
                MyHelper.IsFree();
            }
        }

        private void Refresh()
        {
            this.TLUser = new PagedCollectionView(this.currentData);
        }

        private void DoubleClickItem()
        {
            DateTime now = DateTime.Now;
            if (now.Subtract(_clickTs).TotalMilliseconds <= 200)//
            {
                if (ActionMenuButton.actionControl.Edit.CanExecute(ActionMenuButton.Edit))
                    this.Edit();
                else if (ActionMenuButton.actionControl.View.CanExecute(ActionMenuButton.View))
                    this.View();
            }
            else
            {
                _clickTs = now;
            }
        }

        #endregion

        //Command button action
        public class ActionButton : ICommand
        {
            private UserViewModel viewModel;
            public ActionButton(UserViewModel viewModel)
            {
                this.viewModel = viewModel;
                this.viewModel.PropertyChanged += (s, e) =>
                {
                    if (this.CanExecuteChanged != null)
                    {
                        this.CanExecuteChanged(this, new EventArgs());
                    }
                };
            }

            public bool CanExecute(object parameter)
            {
                if (parameter.ToString().Equals(ActionMenuButton.Delete)
                    || parameter.ToString().Equals(ActionMenuButton.Edit)
                    || parameter.ToString().Equals(ActionMenuButton.View))
                    return this.viewModel.currentUser != null;
                return true;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                switch (parameter.ToString())
                {
                    case ActionMenuButton.Edit: this.viewModel.Edit();
                        break;
                    case ActionMenuButton.Delete: this.viewModel.Delete();
                        break;
                    case ActionMenuButton.Insert: this.viewModel.Insert();
                        break;
                    case ActionMenuButton.Search: this.viewModel.Search();
                        break;
                    case ActionMenuButton.View: this.viewModel.View();
                        break;
                    default: break;
                }
            }
        }
    }
}
